#LineUP Plugin
import sys,urllib,urllib2,urlparse,base64
import xbmcgui, xbmcplugin, xbmcaddon
from BeautifulSoup import BeautifulSoup, SoupStrainer

base_url = sys.argv[0]
addon_handle = int(sys.argv[1])
try:
    from urlparse import parse_qs
except ImportError:
    #python 2.4 compatibility
    from cgi import parse_qs
    urlparse.parse_qs = parse_qs
args = urlparse.parse_qs(sys.argv[2][1:])

#PLUGIN CONSTANTS
plugin_id = 'plugin.video.lineup'
addon = xbmcaddon.Addon(id=plugin_id)

#COMMON PLUGIN FUNCTIONS
#subfolder url link
def build_url(query):
    return base_url + '?' + urllib.urlencode(query)

#chrome web browser act a like
useragent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36'

def getURL(url):
        print '>>>>>LineUP Plugin :: getURL :: url = '+url
        try:
            req = urllib2.Request(url)
            req.add_header('User-Agent', useragent)
            response = urllib2.urlopen(req)
            link=response.read()
            response.close()
        except urllib2.HTTPError, error:
            print 'Error reason: ', error
            return error.read()
        else:
            return link

mode = args.get('mode', None)
 
if mode is None:
    channellist = 'https://californiway.googlecode.com/svn/trunk/plugin.video.lineup/resources/media/channellist.xml'
    data = getURL(channellist)
    soup = BeautifulSoup(data)
    channels = soup.findAll('channel')
    for channel in channels:
        name = base64.b64decode(channel['name'])
        channelurl = base64.b64decode(channel['url'])
        thumb = base64.b64decode(channel['thumb'])
        url = build_url({'mode': 'videolist', 'foldername': name, 'channelurl': channelurl, 'thumb': thumb})
        li = xbmcgui.ListItem(name, iconImage='DefaultFolder.png')
        li.setThumbnailImage(thumb)
        xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=True)
    
    xbmcplugin.endOfDirectory(addon_handle)

elif mode[0] == 'videolist':
    baseurl = args['channelurl'][0]
    data = getURL(baseurl)
    strainer = SoupStrainer(id="channels-browse-content-grid")
    container = BeautifulSoup(data, parseOnlyThese=strainer)
    for video in container.findAll(attrs={'class':'channels-content-item yt-shelf-grid-item'}):
        name = video.find(attrs={'class':'yt-lockup-title'}).a['title']
        watchid = video.find(attrs={'class':'yt-lockup-title'}).a['href'].replace('/watch?v=','')
        thumb = "http://i.ytimg.com/vi/%s/0.jpg" % (watchid)
        url = build_url({'mode': 'play', 'foldername': name.encode('ascii', 'ignore'), 'watchid': watchid})
        li = xbmcgui.ListItem(name, iconImage='DefaultVideo.png')
        li.setThumbnailImage(thumb)
        li.setProperty('IsPlayable', 'true')
        xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=False)
    
    xbmcplugin.endOfDirectory(addon_handle)

elif mode[0] == 'play':
    watchid = args['watchid'][0]
    xbox = xbmc.getCondVisibility("System.Platform.xbox")
    if xbox==True:
        url = "plugin://video/YouTube/?path=/root/video&action=play_video&videoid=" + watchid
    else:
        url = "plugin://plugin.video.youtube/?path=/root/video&action=play_video&videoid=" + watchid
    listitem = xbmcgui.ListItem(path=url)
    xbmcplugin.setResolvedUrl(addon_handle, True, listitem)
